package com.genexususa.eo.facebook.connection;

import com.genexususa.eo.facebook.data.*;
import com.genexususa.eo.facebook.util.Constants;
import com.genexususa.eo.facebook.util.Info;
import com.restfb.Connection;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.json.JsonObject;
import com.restfb.types.Insight;
import com.restfb.types.Page;
import com.restfb.types.Post;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import java.io.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

public class PageManager {

    public void getAllAccountsPageInsights(String startDate, String endDate, String locationFile, Long waitBetweenRequests){
        AccountManager am = new AccountManager();
        ArrayList<String> accounts = am.getAllAccounts();
        ArrayList<Thread> threads = new ArrayList<Thread>();
        for (String account : accounts){

            GetPageInsights getPageInsights = new GetPageInsights(account, startDate, endDate, locationFile);
            getPageInsights.start();
            threads.add(getPageInsights);

            try {
                Thread.sleep(waitBetweenRequests);
            }catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

        }

        for (Thread thread : threads){
            try{
                thread.join();
                //System.out.println(thread.getName() + " ended!");
            }catch (InterruptedException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }

    }

    public void getPageInsights(String accountId, String startDate, String endDate, String locationFile){

        String result = "";

       // FacebookPages facebookPages = new FacebookPages();

        DateTimeFormatter df = DateTimeFormat.forPattern("yyyy-MM-dd");
        DateTime since = df.parseDateTime(startDate);
        DateTime until = df.parseDateTime(endDate);

        HashMap<String, String> info = null;
        try {
            info = Info.getFacebookProperties();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String accessToken = info.get(Constants.ACCESS_TOKEN);

        FacebookClient client = new DefaultFacebookClient(accessToken);

        //Page page = client.fetchObject(accountId, Page.class);

        Connection<Insight> insights = client.fetchConnection(accountId + "/insights",
                Insight.class, Parameter.with("limit", 250),
                Parameter.with("since", since.getMillis() / 1000L),
                Parameter.with("until", until.getMillis() / 1000L));

        FacebookPage facebookPage = new FacebookPage();
        for (Insight insight : insights.getData()){

            if (insight.getDescription().equalsIgnoreCase(Constants.DAILY_NEW_LIKES)){



                for (JsonObject value : insight.getValues()){
                    FacebookPageLikes likes = new FacebookPageLikes();

                    String date = value.get("end_time").toString();
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                    try {
                        Date formattedDate = dateFormat.parse(date);
                        DateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd");

                        likes.Date = newFormat.format(formattedDate);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    likes.Likes = value.getLong("value");

                    //facebookPage.Likes = value.getLong("value");
                    facebookPage.Likes.add(likes);
                }


            }

            if (insight.getDescription().equalsIgnoreCase(Constants.VIRAL_REACH)){


                for (JsonObject value : insight.getValues()){
                    FacebookPageViralReach viralReach = new FacebookPageViralReach();

                    String date = value.get("end_time").toString();
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                    try {
                        Date formattedDate = dateFormat.parse(date);
                        DateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd");

                        viralReach.Date = newFormat.format(formattedDate);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    viralReach.ViralReach = value.getLong("value");

                    //facebookPage.Likes = value.getLong("value");
                    facebookPage.ViralReach.add(viralReach);
                }


            }

            if (insight.getDescription().equalsIgnoreCase(Constants.PAGE_CONSUMPTION)){


                for (JsonObject value : insight.getValues()){
                    FacebookPageConsumption pageConsumption = new FacebookPageConsumption();

                    String date = value.get("end_time").toString();
                    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
                    try {
                        Date formattedDate = dateFormat.parse(date);
                        DateFormat newFormat = new SimpleDateFormat("yyyy-MM-dd");

                        pageConsumption.Date = newFormat.format(formattedDate);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    pageConsumption.PageConsumption = value.getLong("value");

                    //facebookPage.Likes = value.getLong("value");
                    facebookPage.PageConsumption.add(pageConsumption);
                }


            }

        }
        //facebookPages.Pages.add(facebookPage);

        try {

            JAXBContext contextObj = JAXBContext.newInstance(FacebookPage.class);

            Marshaller marshallerObj = contextObj.createMarshaller();
            marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

            StringWriter sw = new StringWriter();

            marshallerObj.marshal(facebookPage, sw);
            result = sw.getBuffer().toString();
            System.out.println(result);
            String s = "";


            FileWriter fw = new FileWriter(locationFile + File.separator + "PageInsights-" + accountId + ".xml");
            BufferedWriter bw = new BufferedWriter(fw);

            bw.write(result);
            bw.flush();
            bw.close();


        } catch (Exception excAux) {

        }


    }


}

class GetPageInsights extends Thread{

    private String accountId;
    private String startDate;
    private String endDate;
    private String locationFile;

    public GetPageInsights(String accountId, String startDate, String endDate, String locationFile){
        this.accountId = accountId;
        this.startDate = startDate;
        this.endDate = endDate;
        this.locationFile = locationFile;
    }

    public void run(){
        PageManager pm = new PageManager();
        pm.getPageInsights(accountId, startDate, endDate, locationFile);
    }

}
